package com.qf.blog.controller;

import com.qf.blog.core.servlet.BaseServlet;
import com.qf.blog.listener.ThymeleafListener;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/PageServlet/*")
public class PageServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1、通过请求地址获取跳转的页面
        String contextPath = req.getContextPath();
        String path = req.getRequestURI().replaceAll(contextPath+"/PageServlet/", "");

        // 直接转发过去发现thymeleaf的标签无法解析，所以这里需要用thymleaf的方式跳转
//        req.getRequestDispatcher("/WEB-INF/templates" + path).forward(req, resp);

//        /templates/【】*.html/
        // uri:/PageServlet/system/index.html
        String page = path.replace(".html", "");
        System.out.println("page:"+page);

        // 2、获取上下文对象
        ServletContext servletContext = req.getServletContext();

        // 3.获取模板引擎对象
        TemplateEngine templateEngine = ThymeleafListener.getTemplateEngine(servletContext);

        // 4.创建一个WebContext对象
        WebContext webContext = new WebContext(req, resp, servletContext);

        // 5.跳转到指定的页面(thymeleaf就会实现渲染)
        templateEngine.process(page, webContext, resp.getWriter());
    }
}
